package web

import (
	"github.com/gin-gonic/gin"
	"github.com/kingwrcy/devNews/provider"
	"strconv"
)

var categoryMap = map[string]string{
	"juejin" : provider.JueJinSource,
	"manong" : provider.MaNong,
	"toutiao" : provider.TouTiao,
}
var categories = map[string]string{
	"juejin" : "掘金",
	"manong" : "码农周刊",
	"toutiao" : "开发者头条",
}

const offset  = 10


func StartServer(storage provider.Storage){
	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()
	r.LoadHTMLGlob("templates/*")


	r.GET("/json/:category/:start", func(c *gin.Context) {
		category := c.Param("category")
		if v, ok := categoryMap[category] ;ok{
			start := c.Param("start")
			s ,err := strconv.Atoi(start)
			if err != nil || s < 0 {
				s = 0
			}
			items := storage.GetByPageSize(v,int64(s),offset)
			c.JSON(200,gin.H{"items":items})
			return
		}
		c.String(404,"not found")
	})

	r.GET("/json/:category", func(c *gin.Context) {
		category := c.Param("category")
		if v, ok := categoryMap[category] ;ok{
			items := storage.GetByPageSize(v,0,offset)
			c.JSON(200,gin.H{"items":items})
			return
		}
		c.String(404,"not found")
	})


	r.GET("/html/:category/:start", func(c *gin.Context) {
		category := c.Param("category")
		if v, ok := categoryMap[category] ;ok{
			start := c.Param("start")
			s ,err := strconv.Atoi(start)
			if err != nil || s < 0 {
				s = 0
			}
			items := storage.GetByPageSize(v,int64(s),offset)
			total := storage.Total(v)
			prev := s - offset -1
			next := s + offset + 1

			if prev < 0 {
				prev = 0
			}
			if next > total - offset {
				next = total - offset
			}

			c.HTML(200,"list.gohtml",gin.H{"items":items,"cc":categories,"category":category,"next":next,"prev":prev})
			return
		}
		c.String(404,"not found")
	})

	r.GET("/html/:category", func(c *gin.Context) {
		category := c.Param("category")
		if _, ok := categoryMap[category] ;ok{
			c.Redirect(302,"/html/"+category+"/0")
		}
	})

	r.Run(":9991")
}